package com.ktjiaoyu.controller;

import com.alibaba.fastjson2.JSON;
import com.ktjiaoyu.entity.SysRole;
import com.ktjiaoyu.entity.SysUser;
import com.ktjiaoyu.service.SysUserService;
import com.ktjiaoyu.service.impl.SysUserServiceImpl;
import com.ktjiaoyu.utils.Constants;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;

@Controller
public class PwdController extends BaseController{
    private static final Logger LOGGER= LoggerFactory.getLogger(SysUserServiceImpl.class);

    @Autowired
    private SysUserService sysUserService;

    @GetMapping("/main/changePwd")
    public String toUser(Model model){
        try {
            return "sys/changePwd";
        }catch (Exception e){
            LOGGER.error("PwdController中的toUser方法执行发生错误。",e);
            throw new RuntimeException(e);
        }
    }

    @PostMapping("/main/changePwd")
    public String updatePwd(@RequestParam("confirm-password")String password){
        try {
            SysUser loginUser=session(Constants.SESSION_USER);
            SysUser sysUser=new SysUser();
            sysUser.setId(loginUser.getId());
            sysUser.setPassword(password);

            boolean info=sysUserService.saveOrUpdate(sysUser);

            session().invalidate();
            return redirect("/login");
        }catch (Exception e){
            LOGGER.error("PwdController中的toUser方法执行发生错误。",e);
            throw new RuntimeException(e);
        }
    }

    @ResponseBody
    @GetMapping("/main/oldPasswordCheck")
    public String pwdExist(@RequestParam("oldPassword") String pwd){
        LOGGER.info("检查用户密码是否正确");
        HashMap<String,Object> resultMap=new HashMap<String,Object>();
        if (StringUtils.isEmpty(pwd)){
            resultMap.put("pass",0);
        }else {
            try {
                SysUser loginUser=session(Constants.SESSION_USER);
                if (loginUser.getPassword().equals(pwd)){
                    resultMap.put("pass",1);
                }else {
                    resultMap.put("pass",0);
                }
            }catch (Exception e){
                LOGGER.error("PwdController中的pwdExist方法执行发生错误。",e);
                resultMap.put("error","出现异常，请联系管理员处理");
            }
        }
        return JSON.toJSONString(resultMap);
    }


}
